package com.mpyy.handler.inventory;

import com.alibaba.fastjson.JSON;
import com.mpyy.pojo.*;
import com.mpyy.service.inventory.ProductInfoMapperServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
public class ProductInfoController {
    @Autowired
    @Qualifier(value = "productInfoMapperServiceImpl")
    private ProductInfoMapperServiceInter productInfoMapperServiceInter;

    /*@PathVariable("employeeid") Integer employeeid*/
    @RequestMapping(value = {"/showProductInfo"})
    @ResponseBody
    public String showAllProductInfoCollect(HttpServletRequest request, ProductInfo productInfo, Paging paging ){
        //获取当前页面
        int page = 1/*Integer.parseInt(request.getParameter("page"))*/;

        //获取每页显示条数
        int limit = 3/*Integer.parseInt(request.getParameter("limit"))*/;

        //通过set方法为Paging赋值
       /* paging.setPage(page);
        paging.setLimit(limit);
        productInfo.setPaging(paging);*/

        List<ProductInfo> productInfos = productInfoMapperServiceInter.showAllProductInfoCollect(productInfo);

        //创建一个Map
        HashMap<Object, Object> inventoryDescHashMap = new HashMap<>();
        inventoryDescHashMap.put("code",0);
        inventoryDescHashMap.put("msg","");
        inventoryDescHashMap.put("count",productInfos.size());
        inventoryDescHashMap.put("data",productInfos);
        return JSON.toJSONString(inventoryDescHashMap);
    }

    /*查询仓库表信息*/
    @RequestMapping(value = {"/searchInventory"})
    @ResponseBody
    public void searchInventory(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<DepotInfo> depotInfos = productInfoMapperServiceInter.searchDepotInfo();

        request.setCharacterEncoding("utf-8");  //防止乱码
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");

        /*开启流*/
        PrintWriter writer = response.getWriter();
        /*改为json格式*/
        writer.print (JSON.toJSONString (depotInfos));
        /*关闭流*/
        writer.close ();
    }

    /*员工信息表*/
    @RequestMapping(value = {"/searchEmployeeInfo"})
    @ResponseBody
    public void searchEmployeeInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<EmployeeInfo> employeeInfos = productInfoMapperServiceInter.searchEmployeeInfo();

        request.setCharacterEncoding("utf-8");  //防止乱码
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");

        /*开启流*/
        PrintWriter writer = response.getWriter();
        /*改为json格式*/
        writer.print (JSON.toJSONString (employeeInfos));
        /*关闭流*/
        writer.close ();
    }

    /*调用查询仓库明细表信息*/
    @RequestMapping(value = {"/searchInventoryDescInfo"})
    @ResponseBody
    public String searchInventoryDescInfo(HttpServletRequest request) throws IOException {
        InventoryDesc inventoryDesc = new InventoryDesc();
        inventoryDesc.setInveDescDepot(request.getParameter("depotName"));
        inventoryDesc.setProIdAndproName(request.getParameter("proIdAndproName"));
        List<InventoryDesc> inventoryDescs = productInfoMapperServiceInter.searchInventoryDescInfo(inventoryDesc);

        //创建一个Map
        HashMap<Object, Object> inventoryDescHashMap = new HashMap<>();
        inventoryDescHashMap.put("code",0);
        inventoryDescHashMap.put("msg","");
        inventoryDescHashMap.put("data",inventoryDescs);
        /*System.out.println("POOOOOOPPO:"+JSON.toJSONString(inventoryDescHashMap));*/
        return JSON.toJSONString(inventoryDescHashMap);
    }

    /*查询商品批次信息*/
    @RequestMapping(value = "/searchCommodityBatch/{proId}",method = RequestMethod.GET)
    @ResponseBody
    public String searchCommodityBatch(@PathVariable("proId") String proId){
        List<InventoryDesc> inventoryDescs = productInfoMapperServiceInter.searchCommodityBatch(proId);

        //创建一个Map
        HashMap<Object, Object> inventoryDescHashMap = new HashMap<>();
        inventoryDescHashMap.put("code",0);
        inventoryDescHashMap.put("msg","");
        inventoryDescHashMap.put("data",inventoryDescs);
        return JSON.toJSONString(inventoryDescHashMap);
    }
    
    /*库存调拨情况列表*/
    @RequestMapping(value = "/searchInventoryAllocationInfo/{depotIdOut}/{depotIdIn}/{empId}/{allotData}/{flag}")
    @ResponseBody
    public String searchInventoryAllocationInfo
    (@PathVariable("depotIdOut") String depotIdOut,
     @PathVariable("depotIdIn") String depotIdIn,
     @PathVariable("empId") String empId,
     @PathVariable("allotData") String allotData,
     @PathVariable("flag") String flag) throws ParseException {
        String startData = allotData.substring(0,10);
        String terminationData = allotData.substring(13,23);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        Date dateStart = simpleDateFormat.parse(startData);
        Date dateTermination = simpleDateFormat.parse(terminationData);

        InventoryAllocation inventoryAllocation = new InventoryAllocation();
        inventoryAllocation.setDepotId(depotIdOut);
        inventoryAllocation.setDepotIds(depotIdIn);
        inventoryAllocation.setEmpId(empId);
        inventoryAllocation.setInvAllotDate(dateStart);
        inventoryAllocation.setInvAllotDates(dateTermination);

        List<InventoryAllocation> inventoryAllocations;
        if(flag.equals("advancedQuerybtn")){
            inventoryAllocations = productInfoMapperServiceInter.searchInventoryAllocationInfo(inventoryAllocation);
        }else{
            inventoryAllocations = productInfoMapperServiceInter.searchInventoryAllocationInfoData(inventoryAllocation);
        }

        //创建一个Map
        HashMap<Object, Object> inventoryDescHashMap = new HashMap<>();
        inventoryDescHashMap.put("code",0);
        inventoryDescHashMap.put("msg","");
        inventoryDescHashMap.put("data",inventoryAllocations);
        return JSON.toJSONString(inventoryDescHashMap);
    }

    /*查询单据的详细信息*/
    @RequestMapping(value = "/searchInventoryAllocationDescInfo/{invAllotId}")
    @ResponseBody
    public String searchInventoryAllocationDescInfo(@PathVariable("invAllotId") String invAllotId){
        List<InventoryAllocationDesc> inventoryAllocationDescs = productInfoMapperServiceInter.searchInventoryAllocationDescInfo(invAllotId);

        //创建一个Map
        HashMap<Object, Object> inventoryDescHashMap = new HashMap<>();
        inventoryDescHashMap.put("code",0);
        inventoryDescHashMap.put("msg","");
        inventoryDescHashMap.put("data",inventoryAllocationDescs);
        return JSON.toJSONString(inventoryDescHashMap);
    }

    /*新增一条库存调拨信息*/
    @RequestMapping(value = "/updateInventoryAllocation/{invAllotld}/{depotIdOut}/{depotIdIn}/{allotData}/{empId}/{invAllotComment}")
    @ResponseBody
    public int updateInventoryAllocation(
            @PathVariable("invAllotld") String invAllotld,
            @PathVariable("depotIdOut") String depotIdOut,
            @PathVariable("depotIdIn") String depotIdIn,
            @PathVariable("allotData") String allotData,
            @PathVariable("empId") String empId,
            @PathVariable("invAllotComment") String invAllotComment) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        Date allotDatas = simpleDateFormat.parse(allotData);

        InventoryAllocation inventoryAllocation = new InventoryAllocation();
        inventoryAllocation.setInvAllotId(invAllotld);
        inventoryAllocation.setDepotId(depotIdOut);
        inventoryAllocation.setDepotIds(depotIdIn);
        inventoryAllocation.setInvAllotDate(allotDatas);
        inventoryAllocation.setEmpId(empId);
        inventoryAllocation.setEmpIds(empId);
        inventoryAllocation.setInvAllotComment(invAllotComment);

        int i = productInfoMapperServiceInter.updateInventoryAllocation(inventoryAllocation);
        return i;
    }

    /*新增调拨明细表信息*/
    @RequestMapping(value = "updateInventoryAllocationDesc/{temporaryStorageArrays}/{invAllotld}")
    @ResponseBody
    public int updateInventoryAllocationDesc(@PathVariable("temporaryStorageArrays") String temporaryStorageArrays,
                                                @PathVariable("invAllotld") String invAllotld) throws Exception {
        //创建一个StringBuffer对象，获取页面传递过来的销售订单明细数据，拼接还原后加入StringBuffer中
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[" + temporaryStorageArrays + "]");

        //调用自定义的转换工具类
        List<InventoryDesc> inventoryDescs = ProSalesUtil.<InventoryDesc>decomposeJsonArray(stringBuffer, InventoryDesc.class);
        System.out.println("kkkk:"+inventoryDescs);

        InventoryAllocationDesc inventoryAllocationDesc = new InventoryAllocationDesc();
        inventoryAllocationDesc.setInvAllotId(invAllotld);

        int row=0;
        for(int i = 0;i < inventoryDescs.size(); i++){
            inventoryAllocationDesc.setProId(inventoryDescs.get(i).getProId());
            inventoryAllocationDesc.setInvAllotDescProName(inventoryDescs.get(i).getInveDescName());
            inventoryAllocationDesc.setInvAllotDescProUnit(inventoryDescs.get(i).getInveDescUnit());
            inventoryAllocationDesc.setInvAllotDescProSize(inventoryDescs.get(i).getInveDescSize());
            inventoryAllocationDesc.setInvAllotDescProBatchNum(inventoryDescs.get(i).getInveDescBatchNum());
            inventoryAllocationDesc.setInvAllotDescProStartDate(inventoryDescs.get(i).getInveDescStartDate());
            inventoryAllocationDesc.setInvAllotDescValidityDate(inventoryDescs.get(i).getInveDescValidityDate());
            inventoryAllocationDesc.setInvAllotDescNum(inventoryDescs.get(i).getInveDescNum());
            inventoryAllocationDesc.setInvAllotDescManufacturer(inventoryDescs.get(i).getInveDescManufacturer());
            inventoryAllocationDesc.setInvAllotDescSellPrice(inventoryDescs.get(i).getInveDescPrice());

            Calendar calendar = Calendar.getInstance();
            String year = String.valueOf(calendar.get(Calendar.YEAR));
            String month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
            if (month.equals("10")) {
                month = "0" + month;
            }
            String day = String.valueOf(calendar.get(Calendar.DATE));
            String hour = String.valueOf(calendar.get(Calendar.HOUR));
            String minute = String.valueOf(calendar.get(Calendar.MINUTE));
            String second = String.valueOf(calendar.get(Calendar.SECOND) + i+1);
            //库存商品明细编号
            inventoryAllocationDesc.setInvAllotDescId("DB" + year + month + day + hour + minute + second);

            row = productInfoMapperServiceInter.updateInventoryAllocationDesc(inventoryAllocationDesc);
        }
        return 0;
    }


    /*修改调出仓库的商品信息*/
    @RequestMapping(value = "/updateInventoryAllocationDescOut/{temporaryStorageArrays}")
    @ResponseBody
    public int updateInventoryAllocationDescOut(@PathVariable("temporaryStorageArrays") String temporaryStorageArrays)throws Exception {
        //创建一个StringBuffer对象，获取页面传递过来的销售订单明细数据，拼接还原后加入StringBuffer中
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[" + temporaryStorageArrays + "]");

        //调用自定义的转换工具类
        List<InventoryDesc> inventoryDescs = ProSalesUtil.<InventoryDesc>decomposeJsonArray(stringBuffer, InventoryDesc.class);

        /*定义一个库存明细表对象*/
        InventoryDesc inventoryDesc = new InventoryDesc();
        int row=0;
        for(int j = 0;j<inventoryDescs.size();j++){
            inventoryDesc.setProId(inventoryDescs.get(j).getProId());
            inventoryDesc.setInveDescDepot(inventoryDescs.get(j).getInveDescDepot());
            inventoryDesc.setInveDescNum(inventoryDescs.get(j).getInveDescNum());
            row = productInfoMapperServiceInter.updateInventoryDescNumber(inventoryDesc);
        }
        /*System.out.println("kkkkkkkk:"+inventoryDescs);
        System.out.println("llllllll:"+row);*/
        return row;
    }


    /*修改调入仓库的商品信息*/
    @RequestMapping(value = "/updateInventoryDescIn/{temporaryStorageArrays}/{depotIdIn}")
    @ResponseBody
    public int updateInventoryDescIn(@PathVariable("temporaryStorageArrays") String temporaryStorageArrays,
                                               @PathVariable("depotIdIn") String depotIdIn) throws Exception {
        //创建一个StringBuffer对象，获取页面传递过来的销售订单明细数据，拼接还原后加入StringBuffer中
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[" + temporaryStorageArrays + "]");
        //调用自定义的转换工具类
        List<InventoryDesc> inventoryDescs = ProSalesUtil.<InventoryDesc>decomposeJsonArray(stringBuffer, InventoryDesc.class);

        /*定义一个库存明细表对象*/
        InventoryDesc inventoryDesc = new InventoryDesc();
        /*调入仓库编号*/
        inventoryDesc.setInveDescDepot(depotIdIn);

        int row=0;
        for(int i = 0;i < inventoryDescs.size(); i++){
            inventoryDesc.setProId(inventoryDescs.get(i).getProId());
            /*查询指定仓库的库存表中是否存在指定的商品*/
            List<InventoryDesc> inventoryDescs1 = productInfoMapperServiceInter.searchInventoryDescInfoAssign(inventoryDesc);

            if(inventoryDescs1.size() > 0){
                System.out.println("存在");
                /*对要调入仓库的商品做修改操作*/
                inventoryDesc.setProId(inventoryDescs.get(i).getProId());
                inventoryDesc.setInveDescNum(inventoryDescs.get(i).getInveDescNum());
                row = productInfoMapperServiceInter.updateInventoryDescNumber(inventoryDesc);
            }else{
                System.out.println("不存在");
                /*对要调入仓库的商品做新增操作*/
                inventoryDesc.setProId(inventoryDescs.get(i).getProId());
                inventoryDesc.setInveDescName(inventoryDescs.get(i).getInveDescName());
                inventoryDesc.setInveDescType(inventoryDescs.get(i).getInveDescType());
                inventoryDesc.setInveDescUnit(inventoryDescs.get(i).getInveDescUnit());
                inventoryDesc.setInveDescSize(inventoryDescs.get(i).getInveDescSize());
                inventoryDesc.setInveDescPostil(inventoryDescs.get(i).getInveDescPostil());
                inventoryDesc.setInveDescManufacturer(inventoryDescs.get(i).getInveDescManufacturer());
                inventoryDesc.setInveDescBatchNum(inventoryDescs.get(i).getInveDescBatchNum());
                inventoryDesc.setInveDescStartDate(inventoryDescs.get(i).getInveDescStartDate());
                inventoryDesc.setInveDescValidityDate(inventoryDescs.get(i).getInveDescValidityDate());
                inventoryDesc.setInveDescInventoryNum(inventoryDescs.get(i).getInveDescNum());
                inventoryDesc.setInveDescPrice(inventoryDescs.get(i).getInveDescPrice());
                inventoryDesc.setInveDescDepot(inventoryDescs.get(i).getInveDescDepot());
                inventoryDesc.setInveDescProState(inventoryDescs.get(i).getInveDescProState());
                inventoryDesc.setInveDescComment(inventoryDescs.get(i).getInveDescComment());
                inventoryDesc.setSupId(inventoryDescs.get(i).getSupId());

                Calendar calendar = Calendar.getInstance();
                String year = String.valueOf(calendar.get(Calendar.YEAR));
                String month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
                if (month.equals("10")) {
                    month = "0" + month;
                }
                String day = String.valueOf(calendar.get(Calendar.DATE));
                String hour = String.valueOf(calendar.get(Calendar.HOUR));
                String minute = String.valueOf(calendar.get(Calendar.MINUTE));
                String second = String.valueOf(calendar.get(Calendar.SECOND) + i+1);
                //库存商品明细编号
                inventoryDesc.setInveDescId("KC" + year + month + day + hour + minute + second);

                row = productInfoMapperServiceInter.updateInventoryDescIn(inventoryDesc);
            }
        }
        return row;
    }

}
